package com.yueshop.product.service.impl;

import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yueshop.common.utils.PageUtils;
import com.yueshop.common.utils.Query;

import com.yueshop.product.dao.CategoryDao;
import com.yueshop.product.entity.CategoryEntity;
import com.yueshop.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * 三级查询方法
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
//        1. 把所有分类数据都先查询出来
        List<CategoryEntity> lists = baseMapper.selectList(null);
//        2. 过滤出一级分类的category
//        3. 在CategoryEntity中定义子分类集合的引用
//        4. 定义一个递归方法查询子分类列表
        List<CategoryEntity> listMenu = lists.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == 0)
                .map(category -> {
                    //嵌套获取每个分类中的子类
                    category.setChildrenCategory(getChildren(category , lists));
                    return category;
                })
//        5. 排序
                .sorted((menu1 , menu2) -> {
                    return (menu2.getSort() == null ? 0 : menu2.getSort()) - (menu1.getSort() == null ? 0 : menu1.getSort());
                })
                .collect(Collectors.toList());
//        返回结果
        return listMenu;
    }

    /**
     * 逻辑删除分类
     * @param asList
     */
    @Override
    public void removeMenuByIds(List<Long> asList) {
        baseMapper.deleteBatchIds(asList);
    }

    /**
     * 递归查询
     */
    private List<CategoryEntity> getChildren(CategoryEntity root , List<CategoryEntity> all) {
        List<CategoryEntity> children = all.stream()
                .filter(categoryEntity -> categoryEntity.getParentCid() == root.getCatId())
                .map(category -> {
                    //嵌套获取每个分类中的子类
                    category.setChildrenCategory(getChildren(category , all));
                    return category;
                })
                .sorted((menu1 , menu2) -> {
                    return (menu2.getSort() == null ? 0 : menu2.getSort()) - (menu1.getSort() == null ? 0 : menu1.getSort());
                })
                .collect(Collectors.toList());

        return children;
    }

}